<?php

namespace App\Http\Controllers\Admin\Sundry;

use App\Exceptions\LogicException;
use App\Http\Controllers\Controller;
use App\Models\Adminer\Admins;
use App\Models\Sundry\Notepad;
use App\Utils\QueryUtil;
use App\Utils\ResUtil;

class NotepadController extends Controller
{

    public function list()
    {
        $request = request()->all();
        $query = Notepad::where(function($query) use($request) {
            QueryUtil::selectBuild($query, $request, [
                ['title', 'like', 'title'],
                ['note', 'like', 'note'],
                ['tags', 'like', 'tags'],
                ['status', '='],
                ['start_at', '>=', 'created_at'],
                ['end_at', '<=', 'created_at'],
                ['id', '='],
            ]);
            $query->where('admin_id', $this->authAdmin()->id);
        });

        $total = $query->count();
        $models = QueryUtil::queryList($query);
        $list = [];
        foreach($models as $i => $v) {
            $list[$i] = $v?->label()?->Explode()->toArray();
        }
        $hasMore = QueryUtil::hasMore(sizeof($list));
        return $this->ok(compact('list', 'total', 'hasMore'));
    }

    public function edit()
    {
        $data = request()->all();
        $rule = [
            'id' => '',
            'title' => 'string|required',
            'note' => 'string|required',
            'tags' => '',
        ];
        $validator = validatorService()->checkValidator($rule, $data, Notepad::$fillables);
        if ($validator['code'] != 200) {
            throw new LogicException($validator['data']);
        }

        if($data['id'] ?? '') {
            $project = Notepad::find($data['id']);
            if(!$project) {
                throw new LogicException(ResUtil::NOT_DATA);
            }
        } else {
            $project = new Notepad();
            $project->status = Notepad::STATUS_INIT;
            $project->admin_id = $this->authAdmin()->id;
        }

        $tags = '';
        if(!empty($data['tags']) && is_array($data['tags'] ?? '')) {
            $tags = implode(',', $data['tags']);
        }
        $project->fill([
            'title' => $data['title'] ?? '',
            'tags' => $tags,
            'note' => $data['note'] ?? '',
        ]);
        $project->save();
        return $this->ok();
    }

    public function enable()
    {
        $data = request()->all();
        $rule = [
            'id' => 'integer|required',
            'status' => 'integer|required|in:1,2',
        ];
        $validator = validatorService()->checkValidator($rule, $data, Notepad::$fillables);
        if ($validator['code'] != 200) {
            throw new LogicException($validator['data']);
        }
        $cate = Notepad::find($data['id']);
        if(!$cate) {
            throw new LogicException(ResUtil::NOT_DATA);
        }
        $cate->status = $data['status'];
        $cate->save();
        return $this->ok();
    }
}
